import axios from "axios";
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: 'http://localhost:8088',
  timeout: 10000,
});

// request 拦截器
service.interceptors.request.use(
  (config) => {
    // 在这里可以设置请求头、请求参数等
    const token = localStorage.getItem('token');
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    // 判断响应是否为文件流（Excel导出）
    const contentType = response.headers['content-type'];
    
    // 如果是文件流类型，直接返回完整response
    if (contentType && contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
      return response;
    }
    
    // 普通JSON响应处理
    const { data } = response;
    if (data.code !== 200) {
      ElMessage.error(data.message || '数据查询失败');
      return Promise.reject(data || "Error");
    } else {
      return data;
    }
  },
  (error) => {
    console.log(error);
    ElMessage.error('请求失败：' + (error.message || '网络错误'));
    return Promise.reject(error);
  }
);

export default service;